import 'package:flutter/material.dart';
import 'package:flutterlearnapp/provider.dart';
import 'widgets/index.dart';
import 'routes/index.dart';
import 'package:common_utils/common_utils.dart';
import 'package:go_router/go_router.dart';

/// @author jltxseo
///         Created by junlintianxia on 2020/04/21.
void main() async {
  LogUtil.init(isDebug: true);
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    final GoRouter _router = GoRouter(
      routes: <RouteBase>[
        GoRoute(
          path: '/',
          builder: (BuildContext context, GoRouterState state) {
            return MyHomePage(title: 'Flutter Demo');
          },
          routes: <RouteBase>[
            GoRoute(
              path: 'newRoute',
              builder: (BuildContext context, GoRouterState state) {
                return NewRoute();
              },
            ),
            GoRoute(
              path: 'tip',
              builder: (BuildContext context, GoRouterState state) {
                return TipRoute(
                  text: state.uri.queryParameters['text'] ?? "我是默认提示",
                );
              },
            ),
            GoRoute(
              path: 'tip2',
              builder: (BuildContext context, GoRouterState state) {
                return TipRoute(
                  text: state.uri.queryParameters['text'] ?? "我是默认提示",
                );
              },
            ),
          ],
          redirect: (BuildContext context, GoRouterState state) {
            // 检查路径是否存在
            if (state.matchedLocation.isEmpty) {
              return 'newRoute';
            }
            return null; // 如果路径存在，返回 null
          },
        ),
      ],
      redirect: (BuildContext context, GoRouterState state) {
        // 检查路径是否存在
        if (state.matchedLocation.isEmpty) {
          return '/newRoute';
        }
        return null; // 如果路径存在，返回 null
      },
    );

    return MaterialApp.router(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      routerConfig: _router,
    );
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      onGenerateRoute: (RouteSettings settings) {
        return MaterialPageRoute(builder: (context) {
          String routeName = settings.name as String;
          if (routeName == "tip") {
            return TipRoute(text: settings.arguments as String);
          } else {
            return NewRoute();
          }
        });
      },
      routes: {
        "tip2": (context) {
          return TipRoute(text: ModalRoute.of(context)?.settings.arguments as String);
        }
      },
      home: MyHomePage(title: 'Flutter Demo'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  MyHomePageState createState() => MyHomePageState();
}

class MyHomePageState extends State<MyHomePage> {
  void _openPage(BuildContext context, PageInfo pageInfo) {
    Navigator.of(context).push(MaterialPageRoute(builder: (context) {
      if (!pageInfo.withScaffold) {
        return pageInfo.builder(context);
      }

      return PageScaffold(
        title: pageInfo.title,
        body: pageInfo.builder(context),
        padding: pageInfo.padding,
      );
    }));
  }

  List<Widget> _generateItem(BuildContext context, List<PageInfo> children) {
    return children.map<Widget>((page) {
      return ListTile(
        title: Text(page.title),
        trailing: Icon(Icons.keyboard_arrow_right),
        onTap: () => _openPage(context, page),
      );
    }).toList();
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: ListView(
        children: <Widget>[
          ExpansionTile(
            title: Text("第一个Flutter应用"),
            children: _generateItem(context, [
              PageInfo("RouterTestRoute", (ctx) => RouterTestRoute(),
                  padding: false),
              PageInfo("PageRouter", (ctx) => PageLearn(),
                  padding: false)
            ]),
          ),
          ExpansionTile(
            title: Text("基础组件"),
            children: _generateItem(context, [
              PageInfo("图片伸缩", (ctx) => ImageAndIconRoute(), padding: false),
              PageInfo("Echo", (ctx) => Echo(text: "hello world")),
              PageInfo("Context测试", (ctx) => ContextRoute()),
              PageInfo("State生命周期", (ctx) => CounterRoute()),
              PageInfo("获取State对象", (ctx) => RetrieveStateRoute()),
              PageInfo("Widget管理自身状态", (ctx) => TapboxA()),
              PageInfo("父Widget管理子Widget的状态", (ctx) => ParentWidget()),
              PageInfo("混合状态管理", (ctx) => ParentWidgetC()),
              PageInfo("文本、字体样式", (ctx) => TextRoute()),
              PageInfo("按钮", (ctx) => ButtonRoute()),
              PageInfo("单选开关和复选框", (ctx) => SwitchAndCheckBoxRoute()),
              PageInfo("输入框", (ctx) => FocusTestRoute()),
              PageInfo("进度条", (ctx) => ProgressRoute()),
            ]),
          ),
          ExpansionTile(
            title: Text("布局类组件"),
            children: _generateItem(context, [
              PageInfo("线性布局Row,Column", (ctx) => RowColumnRoute()),
              PageInfo("Column居中", (ctx) => CenterColumnRoute()),
              PageInfo("Column的宽度指定为屏幕宽度", (ctx) => ConstrainedBoxRoute()),
              PageInfo("Container,Column特殊情况", (ctx) => ContainerRoute()),
              PageInfo("表格布局", (ctx) => TableRoute()),
              PageInfo("弹性布局Flex，Expanded", (ctx) => FlexLayoutTestRoute()),
              PageInfo("流式布局Wrap", (ctx) => WrapRoute()),
              PageInfo("流式布局Flow", (ctx) => FlowRoute()),
            ]),
          ),
          ExpansionTile(
            title: Text("功能性组件"),
            children: _generateItem(context, [
              PageInfo("导航返回拦截WillPopScope", (ctx) => WillPopScopeTestRoute()),
              PageInfo("数据共享（InheritedWidget）", (ctx) => InheritedWidgetTestRoute()),
              PageInfo("跨组件状态管理(Provider)", (ctx) => ProviderRoute()),
            ]),
          ),
        ],
      ),
    );
  }
}
